package com.neuedu.his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.his.mapper.*;
import com.neuedu.his.po.*;
import com.neuedu.his.service.RegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RegisterServiceImpl extends ServiceImpl<RegisterMapper, Register> implements RegisterService {



    private static final Logger logger = LoggerFactory.getLogger(RegisterServiceImpl.class);

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RegistlevelMapper registLevelMapper;

    @Autowired
    private ConstantitemMapper constantItemMapper;

    @Override
    @Transactional
    public Map<String, Object> calculateAndSaveRegistration(Register register) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到的挂号信息: {}", register);

            // 验证必填字段
            validateRegistration(register);

            // 生成病历号
            register.setCasenumber(generateCaseNumber());

            // 计算并设置年龄
            register.setAge(calculateAge(register.getBirthdate(), register.getVisitdate()));
            register.setAgetype("岁");

            // 设置默认值
            register.setSettleid(1); // 默认结算类别为自费
            register.setNoon(calculateNoon()); // 设置午别
            register.setRegisttime(new Date()); // 设置挂号时间为当前时间
            register.setVisitstate(1); // 默认看诊状态为待就诊

            // 保存挂号信息
            boolean success = save(register);
            if (!success) {
                throw new RuntimeException("保存挂号信息失败");
            }

            // 返回成功结果
            result.put("success", true);
            result.put("registerId", register.getId());
            result.put("caseNumber", register.getCasenumber());
            result.put("totalFee", calculateTotalFee(register.getRegistleid(), "是".equals(register.getIsbook())));
            logger.info("挂号操作成功: {}", result);
        } catch (Exception e) {
            logger.error("挂号操作失败", e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    // 生成病历号
    private String generateCaseNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        Random random = new Random();
        int randomNum = random.nextInt(9000) + 1000; // 生成4位随机数
        return dateStr + randomNum;
    }

    private void validateRegistration(Register register) {
        if (register.getRealname() == null || register.getRealname().trim().isEmpty()) {
            throw new IllegalArgumentException("姓名不能为空");
        }
        if (register.getGender() == null) {
            throw new IllegalArgumentException("性别不能为空");
        }
        if (register.getBirthdate() == null) {
            throw new IllegalArgumentException("出生日期不能为空");
        }
        if (register.getVisitdate() == null) {
            throw new IllegalArgumentException("看诊日期不能为空");
        }
        if (register.getDeptid() == null) {
            throw new IllegalArgumentException("科室不能为空");
        }
        if (register.getUserid() == null) {
            throw new IllegalArgumentException("医生不能为空");
        }
        if (register.getRegistleid() == null) {
            throw new IllegalArgumentException("挂号级别不能为空");
        }
    }

    private String calculateNoon() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        return hour < 12 ? "上午" : "下午";
    }

    @Override
    public List<Department> getDepartments() {
        return departmentMapper.selectList(new QueryWrapper<Department>().eq("DelMark", 1));
    }

    @Override
    public List<User> getDoctorsByDeptId(Integer deptId) {
        return userMapper.selectList(new QueryWrapper<User>()
                .eq("DeptID", deptId)
                .eq("IsScheduling", "是")
                .eq("DelMark", 1));
    }

    @Override
    public List<Registlevel> getRegistLevels() {
        return registLevelMapper.selectList(new QueryWrapper<Registlevel>().eq("DelMark", 1));
    }

    @Override
    public List<Constantitem> getGenders() {
        return constantItemMapper.selectList(new QueryWrapper<Constantitem>()
                .eq("ConstantTypeID", 1)  // 性别类型ID=1
                .in("ConstantName", "男", "女")
                .eq("DelMark", 1));
    }

    @Override
    public int calculateAge(Date birthDate, Date visitDate) {
        if (birthDate == null || visitDate == null) {
            throw new IllegalArgumentException("出生日期和看诊日期不能为空");
        }

        Calendar birthCalendar = Calendar.getInstance();
        birthCalendar.setTime(birthDate);
        Calendar visitCalendar = Calendar.getInstance();
        visitCalendar.setTime(visitDate);

        int age = visitCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
        if (visitCalendar.get(Calendar.DAY_OF_YEAR) < birthCalendar.get(Calendar.DAY_OF_YEAR)) {
            age--;
        }
        return age;
    }

    @Override
    public BigDecimal getRegistFeeById(Integer registLevelId) {
        Registlevel level = registLevelMapper.selectById(registLevelId);
        return level != null ? level.getRegistfee() : BigDecimal.ZERO;
    }

    @Override
    public BigDecimal calculateTotalFee(Integer registLevelId, boolean isBook) {
        BigDecimal fee = getRegistFeeById(registLevelId);
        if (isBook) {
            fee = fee.add(BigDecimal.ONE); // 加1元病历本费用
        }
        return fee;
    }
}